package net.csdn.business.mirror.listen;

import lombok.extern.slf4j.Slf4j;
import net.csdn.business.mirror.entity.bean.ScheduleTask;
import net.csdn.business.mirror.enums.TaskType;
import net.csdn.business.mirror.scheduled.handler.TaskRegister;
import net.csdn.business.mirror.service.ScheduleTaskService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Component
public class TasksChangeListener {
    @Autowired
    private ScheduleTaskService scheduleTaskService;

    @Autowired
    private TaskRegister taskRegister;

    @PostConstruct
    private void initialize() {
        List<ScheduleTask> lists = scheduleTaskService.validList();
        if (CollectionUtils.isNotEmpty(lists)) {
            for (ScheduleTask item : lists) {
                taskRegister.submit(TaskType.RELEASE, item);
            }
        }
    }

    public void changeTasks() {
        try {
            taskRegister.destroy();
            List<ScheduleTask> lists = scheduleTaskService.validList();
            if (CollectionUtils.isNotEmpty(lists)) {
                for (ScheduleTask item : lists) {
                    taskRegister.submit(TaskType.RELEASE, item);
                }
            }
        } catch (Exception e) {
            log.error("changeTasks error!!", e);
        }
    }
}
